#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
#include <memory>
#include "Log.hpp"
#include "InetAddr.hpp"

namespace socket_ns
{
    using namespace log_ns;
    class Socket;
    using SockSPtr = std::shared_ptr<Socket>;
    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERR
    };

    static const int gbacklog = 8;

    // 设计模式：模板方法模式
    // 基类，Socket 类
    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void CreateBindOrDie(uint16_t port) = 0;
        virtual void CreateListenOrDie(int backlog = gbacklog) = 0;
        virtual int Acceptor(InetAddr* client_ddr) = 0;
        virtual bool Connetor(const std::string& peerip, uint16_t peerport) = 0;
        virtual void Close() = 0;
        virtual int Sockfd() = 0;
        virtual void ReuseAddr() = 0;

        virtual ssize_t Recv(std::string *out) = 0;
        virtual ssize_t Send(const std::string &in) = 0;

    public:
        // 服务端
        void BuildListenSocket(uint16_t port)
        {
            CreateSocketOrDie();
            ReuseAddr();
            CreateBindOrDie(port);
            CreateListenOrDie();
        }

        // 客户端
        bool BuildClientSocket(const std::string& peerip, uint16_t peerport)
        {
            CreateSocketOrDie();
            return Connetor(peerip, peerport);
        }
    };

    class TcpSoket : public Socket
    {
    public:
        TcpSoket()
        {
        }
        TcpSoket(int sockfd) : _sockfd(sockfd)
        {
        }

        void CreateSocketOrDie() override
        {
            // 1.创建 sockfd
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "create sockfd error\n");
                exit(SOCKET_ERROR);
            }
            LOG(INFO, "create sockfd success, sockfd: %d\n", _sockfd);
        }

        void CreateBindOrDie(uint16_t port) override
        {
            // 2.bind
            struct sockaddr_in server;
            server.sin_family = AF_INET;
            server.sin_port = htons(port); // 别忘了转换字节序
            server.sin_addr.s_addr = INADDR_ANY;

            if (::bind(_sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
            {
                LOG(FATAL, "bind error\n");
                exit(BIND_ERROR);
            }
            LOG(INFO, "bind success\n");
        }

        // 缺省参数，声明与实现任一方写即可
        void CreateListenOrDie(int backlog) override
        {
            // 3.listen
            if (::listen(_sockfd, gbacklog) < 0)
            {
                LOG(FATAL, "listen error\n");
                exit(LISTEN_ERR);
            }
            LOG(INFO, "listen success\n");
        }

        int Acceptor(InetAddr* client_ddr) override
        {
            // 4.accept
            struct sockaddr_in client;
            memset(&client, 0, sizeof(client));
            socklen_t len = sizeof(client);
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                return -1;
            }

            // 获取连接成功
            *client_ddr = InetAddr(client);
            // LOG(INFO, "get a new link, client info: %s, sockfd: %d\n", client_ddr->AddrStr().c_str(), sockfd);
            // 之后要使用 sockfd 来进行通信
            return sockfd;
        }

        bool Connetor(const std::string& peerip, uint16_t peerport)
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(peerport);
            inet_pton(AF_INET, peerip.c_str(), &server.sin_addr);

            int n = connect(_sockfd, (struct sockaddr*)&server, sizeof(server));
            if (n < 0)
            {
                return false;
            }
            return true;
        }

        void Close()
        {
            if (_sockfd > 0)
            {
                close(_sockfd);
            }
        }

        int Sockfd()
        {
            return _sockfd;
        }

        ssize_t Recv(std::string *out) override
        {
            char buffer[4096];
            int n = recv(_sockfd, buffer, sizeof(buffer)-1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                *out += buffer;
            }

            return n;
        }

        ssize_t Send(const std::string &in) override
        {
            int n = send(_sockfd, in.c_str(), in.size(), 0);
            return n;
        }

        void ReuseAddr()
        {
            int opt = 1;
            ::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        }
        
        ~TcpSoket()
        {
        }

    private:
        int _sockfd; // 可以是 listensockfd，也可以是普通 sockfd
    };
}
